<template>
  <div>
    <!-- 添加和修改课时表单 -->
    <el-dialog :visible="dialogFormVisible" :title="title" @close="close()">
      <el-form :model="video" >
        <el-form-item label-width="formLableWidth" label="课时标题">
          <el-input v-model="video.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label-width="formLableWidth" label="课时排序">
          <el-input-number v-model="video.sort" :min="0"/>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio-group v-model="video.free">
            <el-radio :label="true">免费</el-radio>
            <el-radio :label="false">默认</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button :disabled="flag" type="primary" @click="saveOrUpdateVideo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import videoApi from '@/api/video'
export default {
  data() {
    return {
      title: '新增课时',
      dialogFormVisible: false,
      video: {
        sort: 0,
        free: false
      },
      flag: false
    }
  },

  methods: {
    open() {
      this.dialogFormVisible = true
    },

    close() {
      this.dialogFormVisible = false
    },

    saveOrUpdateVideo() {
      // 禁用提交按钮
      this.flag = true
      if (!this.video.id) {
        this.saveVideo()
      } else {
        this.updateVideo()
      }
    },

    saveVideo() {
      // 提交新增请求
      this.video.courseId = this.$parent.$parent.courseId
      videoApi.saveVideo(this.video).then(response => {
        // 刷新章节课时列表
        this.$parent.getChapterNestedList()
        this.$message.success(response.message)
        // 关闭对话框
        this.close()
        // 清楚缓存
        this.video = {
          sort: 0,
          free: false
        }
        // 设置提交按钮可用
        this.flag = false
      })
    },
    getVideo(VideoId) {
      // 查询要更新的chapter数据回显
      this.title = '更新课时'
      videoApi.getVideo(VideoId).then(response => {
        this.video = response.data.item
        this.video.free = response.data.item.free
        this.dialogFormVisible = true
      })
    },
    updateVideo() {
      videoApi.updateVideo(this.video).then(response => {
        this.$parent.getChapterNestedList()
        this.$message.success(response.message)
        // 关闭对话框
        this.close()
        // 清楚缓存
        this.video = {
          sort: 0,
          free: false
        }
        // 设置提交按钮可用
        this.flag = false
      })
    }
  }
}
</script>
